package com.szt.sy.controller.system.sharefile;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.google.common.collect.Lists;
import com.szt.sy.anontation.Authority;
import com.szt.sy.anontation.AuthorityConfig;
import com.szt.sy.common.AuthorityCommon;
import com.szt.sy.config.ApplicationConfig;
import com.szt.sy.controller.base.AdminBaseController;
import com.szt.sy.entity.system.ShareFile;
import com.szt.sy.service.system.sharefile.ShareFileService;
import com.szt.sy.util.date.DateUtil;
import com.szt.sy.util.excel.ObjectExcelView;
import com.szt.sy.util.web.FileUpload;
import com.szt.sy.vo.rep.base.RepBaseVO;

/***
 * 共享文件控制器
 * 
 * @author wwy
 *
 */
@Controller
@AuthorityConfig(prefix = "/admin/sharefile/list")
@RequestMapping(value = "admin/sharefile")
public class ShareFileController extends AdminBaseController {
	
	@Autowired
	private ShareFileService sharefileService;
	
	@Autowired
	private ApplicationConfig applicationConfig;
	
	/**
	 * 去列表页面
	 *
	 * @param @
	 */
	@Authority(name = AuthorityCommon.LIST)
	@GetMapping(value = "/list")
	public ModelAndView goPage(@RequestParam Map<String, Object> map) {
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("system/sharefile/sharefile_list");
		mv.addObject("queryParam", map);
		// 按钮权限
		
		return mv;
	}
	
	/**
	 * 列表
	 *
	 * @param page
	 * @
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Authority(name = AuthorityCommon.LIST)
	@PostMapping(value = "/list")
	@ResponseBody
	public RepBaseVO list(Page<ShareFile> page, @RequestParam Map<String, Object> map) {
		RepBaseVO repVO = new RepBaseVO<>();
		processParams(map);
		// 列出ShareFile列表
		page = sharefileService.list(new Page<ShareFile>(page.getCurrent(), page.getSize()), map);
		List<ShareFile> varList = page.getRecords();
		Map<String, Object> resultInfo = new HashMap<>(2);
		resultInfo.put("data", varList);
		resultInfo.put("total", page.getTotal());
		return repVO.setCommonSuccess().setData(resultInfo);
	}
	
	/**
	 * 去新增页面
	 *
	 * @param @
	 */
	@Authority(name = AuthorityCommon.ADD)
	@GetMapping(value = "/add")
	public ModelAndView goAdd(@RequestParam Map<String, Object> map) {
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("system/sharefile/sharefile_edit");
		ShareFile entity = new ShareFile();
		mv.addObject("msg", "add");
		mv.addObject("entity", entity);
		mv.addObject("pd", map);
		return mv;
	}
	
	/**
	 * 保存
	 *
	 * @param @
	 */
	@Authority(name = AuthorityCommon.ADD)
	@PostMapping(value = "/add")
	@ResponseBody
	public RepBaseVO save(ShareFile entity, @RequestPart(value = "uploadFile") MultipartFile multipartFile) {
		RepBaseVO repVO = new RepBaseVO();
		if (multipartFile != null) {
			// 执行上传
			String fileName = FileUpload.fileUp(multipartFile, applicationConfig.getUploadFileLocation(),
					IdWorker.getId() + "");
			String fileUrl = applicationConfig.getFileServerPrefix() + "/uploads/" + fileName;
			entity.setFileurl(fileUrl);
		}
		
		entity.setVersion(1L);
		entity.setAddDate(new Date());
		sharefileService.insert(entity);
		return repVO.setCommonSuccess();
	}
	
	/**
	 * 去修改页面
	 *
	 * @param @
	 */
	@Authority(name = AuthorityCommon.EDIT)
	@GetMapping(value = "/edit")
	public ModelAndView goEdit(Long id) {
		ModelAndView mv = this.getModelAndView();
		// 根据ID读取
		ShareFile entity = sharefileService.selectById(id);
		mv.setViewName("system/sharefile/sharefile_edit");
		mv.addObject("msg", "edit");
		mv.addObject("entity", entity);
		return mv;
	}
	
	/**
	 * 修改
	 *
	 * @param @
	 */
	@Authority(name = AuthorityCommon.EDIT)
	@PostMapping(value = "/edit")
	@ResponseBody
	public RepBaseVO edit(ShareFile entity, @RequestPart(value = "uploadFile") MultipartFile multipartFile) {
		RepBaseVO repVO = new RepBaseVO<>();
		if (multipartFile != null) {
			// 执行上传
			String fileName = FileUpload.fileUp(multipartFile, applicationConfig.getUploadFileLocation(),
					IdWorker.getId() + "");
			String fileUrl = applicationConfig.getFileServerPrefix() + fileName;
			entity.setFileurl(fileUrl);
		}
		sharefileService.updateById(entity);
		return repVO.setCommonSuccess();
	}
	
	/**
	 * 删除
	 *
	 * @param out
	 * @
	 */
	@Authority(name = AuthorityCommon.DELETE)
	@PostMapping(value = "/delete")
	@ResponseBody
	public RepBaseVO delete(Long id) {
		sharefileService.deleteById(id);
		return RepBaseVO.newIntance().setCommonSuccess();
	}
	
	/**
	 * 批量删除
	 *
	 * @param @
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Authority(name = AuthorityCommon.DELETE)
	@PostMapping(value = "/deleteAll")
	@ResponseBody
	public RepBaseVO deleteAll(String ids) {
		RepBaseVO repVO = new RepBaseVO<>();
		if (null != ids && !"".equals(ids)) {
			String[] idArray = ids.split(",");
			sharefileService.deleteBatchIds(Lists.newArrayList(idArray));
			
		}
		return repVO.setCommonSuccess();
	}
	
	/**
	 * 导出到excel
	 *
	 * @param @
	 */
	@Authority(name = AuthorityCommon.LIST)
	@PostMapping(value = "/excel")
	public ModelAndView exportExcel(@RequestParam Map<String, Object> map) {
		ModelAndView mv = new ModelAndView();
		processParams(map);
		Map<String, Object> dataMap = new HashMap<>(2);
		List<String> titles = new ArrayList<>();
		titles.add("文件名");
		titles.add("文件地址");
		titles.add("备注");
		dataMap.put("titles", titles);
		List<ShareFile> varOList = sharefileService.listAll(map);
		List<Map<String, Object>> varList = new ArrayList<>();
		for (ShareFile entity : varOList) {
			Map<String, Object> vpd = new HashMap<>(3);
			vpd.put("var1", entity.getFilename());
			vpd.put("var2", entity.getFileurl());
			vpd.put("var3", entity.getRemark());
			varList.add(vpd);
		}
		
		dataMap.put("varList", varList);
		ObjectExcelView erv = new ObjectExcelView();
		mv = new ModelAndView(erv, dataMap);
		return mv;
	}
	
	/***
	 * 处理输入参数
	 *
	 * @param map
	 */
	private void processParams(Map<String, Object> map) {
		String sStartDate = (String) map.get("lastStart");
		String sEndDate = (String) map.get("lastEnd");
		if (StringUtils.isBlank(sStartDate)) {
			map.put("lastStart", null);
		} else {
			map.put("lastStart", DateUtil.getStartTimeOfDate(sStartDate));
		}
		if (StringUtils.isBlank(sEndDate)) {
			map.put("lastEnd", null);
		} else {
			map.put("lastEnd", DateUtil.getEndTimeOfDate(sEndDate));
		}
	}
	
	/***
	 * 上传文件
	 *
	 * @param file
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	@ResponseBody
	public RepBaseVO uploadFile(@RequestPart(value = "upfile") MultipartFile multipartFile) throws IOException {
		RepBaseVO repVO = new RepBaseVO<>();
		Map<String, Object> retMes = new HashMap<>(3);
		// 执行上传
		String fileName = FileUpload.fileUp(multipartFile, applicationConfig.getUploadFileLocation(),
				IdWorker.getId() + "");
		
		retMes.put("original", multipartFile.getOriginalFilename());
		retMes.put("url", applicationConfig.getFileServerPrefix() + fileName);
		retMes.put("title", multipartFile.getOriginalFilename());
		repVO.setCommonSuccess().setData(retMes);
		return repVO;
	}
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(format, true));
	}
}
